package com.huang.controller;


import cn.hutool.crypto.SecureUtil;
import com.huang.pojo.*;
import com.huang.service.AdminService;
import com.huang.service.StudentService;
import com.huang.service.TeacherService;
import com.huang.util.MailUtils;
import com.huang.util.UuidUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class StudentController {

    @Autowired
    @Qualifier("AdminServiceImpl")
    private AdminService adminService;
    @Autowired
    @Qualifier("TeacherServiceImpl")
    private TeacherService teacherService;
    @Autowired
    @Qualifier("StudentServiceImpl")
    private StudentService studentService;

    //学生注册
    @RequestMapping("/student/goRegister")
    public String goRegister() {
        return "studentRegister";
    }

    @RequestMapping("/student/register")
    public String register(Student student, Model model, HttpSession session, @RequestParam("checkCode") String checkCode) throws IOException {

        //验证验证码是否正确
        System.out.println("前端输入的验证码：" + checkCode);
        String code_session = (String) session.getAttribute("checkCode_session");//提取生成的验证码
        session.removeAttribute("checkCode_session");//为了保证验证码只能使用一次
        //比较
        if (!checkCode.equals(code_session)) {
            //验证码错误
            model.addAttribute("studentRegisterMsgError", "验证码有误");
            return "studentRegister";
        }

        if (studentService.findStudentByNo(student) != null) {
            model.addAttribute("studentRegisterMsgError", "此学号已经被注册过，请核实");
            return "studentRegister";
        }

        //设置激活码
        student.setStudentCode(UuidUtil.getUuid());
        //设置激活状态
        student.setStudentStatus("F");
        //加密密码
        student.setStudentPwd(SecureUtil.md5(student.getStudentPwd()));

        if (studentService.registerStudent(student) != 0) {
            model.addAttribute("studentRegisterMsgRight", "注册成功，请查收邮件进行激活账号方可登陆");
            //发送激活邮件
            String content = "<a href='http://localhost:8080/student/toActivation?studentCode=" + student.getStudentCode() + "'>确认激活学生素质拓展管理系统</a>" +
                    "<br>或者访问http://localhost:8080/student/toActivation?studentCode=" + student.getStudentCode();
            MailUtils.sendMail(student.getStudentEmail(), content, "激活邮件");
            return "studentRegister";
        } else {
            model.addAttribute("studentRegisterMsgError", "注册失败");
            return "studentRegister";
        }
    }

    //学生邮件激活
    @RequestMapping("/student/toActivation")
    public String toActivation(Student student, Model model) {
        student.setStudentStatus("T");
        System.out.println(student);
        if (studentService.activationAccount(student) != 0) {
            model.addAttribute("activationMsg", "Correct");
            return "studentPassActivation";
        } else {
            model.addAttribute("activationMsg", "Error");
            return "studentPassActivation";
        }
    }

    //学生登陆
    @RequestMapping("/student/goLogin")
    public String goLogin() {
        return "studentLogin";
    }

    @RequestMapping("/student/login")
    public String login(@RequestParam("checkCode") String checkCode, Student student, Model model, HttpSession session) {
        //加密密码
        student.setStudentPwd(SecureUtil.md5(student.getStudentPwd()));

        System.out.println("学生登陆" + checkCode);
        System.out.println("session中的" + session.getAttribute("checkCode_session"));
        if (!(checkCode.equals(session.getAttribute("checkCode_session")))) {
            model.addAttribute("checkMsg", "验证码输入有误");
            return "studentLogin";
        }

        Student loginStudent = studentService.loginStudent(student);
        System.out.println("loginStudent" + loginStudent);
        if (loginStudent != null) {
            if (!loginStudent.getStudentStatus().equals("T")) {
                model.addAttribute("loginErrorMsg", "账号未激活,已给您发送激活邮件，请注意查收");
                //发送激活邮件
                String content = "<a href='http://localhost:8080/student/toActivation?studentCode=" + loginStudent.getStudentCode() + "'>确认激活学生素质拓展管理系统</a>" +
                        "<br>或者访问http://localhost:8080/student/toActivation?studentCode=" + loginStudent.getStudentCode();
                MailUtils.sendMail(loginStudent.getStudentEmail(), content, "激活邮件");
                return "studentLogin";
            }
            session.setAttribute("studentData", loginStudent);
            model.addAttribute("student", loginStudent);

            //学生加载头像
            UserAvatar userAvatar=new UserAvatar();
            userAvatar.setUserNo(loginStudent.getStudentNo());
            userAvatar=studentService.JudgeAvatar(userAvatar);
            model.addAttribute("userAvatar",userAvatar);

            //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            //学生活动日志登陆时间记录
            UserDiary userDiary=new UserDiary();
            userDiary.setUserNo(loginStudent.getStudentNo());
            Date now = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
            String time = dateFormat.format(now);
            userDiary.setUserLoginTime(time);
            if(studentService.stuLoginRecord(userDiary)!=0){
                System.out.println("登陆时间已成功记录"+time);
                session.setAttribute("stuLoginTime",time);
            }
            //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

            return "studentIndex";
        } else {
            model.addAttribute("loginErrorMsg", "账号或密码有误");
            return "studentLogin";
        }
    }

    //学生查看管理员公告
    @RequestMapping("/student/toViewNotice")
    public String toViewNotice(Model model,HttpSession session){
        //加载管理员发布的公告
        Announcement announcement = new Announcement();
        announcement.setNoticeStatus("T");
        List<Announcement> list = studentService.showNoticeStu(announcement);
        model.addAttribute("list", list);

        return "studentViewNotice";
    }

    //学生完善基本信息
    @RequestMapping("/student/goImprove")
    public String goImprove(Student student, Model model,HttpSession session) {
        UserAvatar userAvatar=new UserAvatar();
        userAvatar.setUserNo(student.getStudentNo());
        model.addAttribute("userAvatar",studentService.JudgeAvatar(userAvatar));
        model.addAttribute("student", studentService.findStudentByNo(student));

        return "studentImproveMsg";
    }

    @RequestMapping("/student/Improve")
    public String improve(Student student, Model model,HttpSession session) {
        if (studentService.improveStudentMsg(student) != 0) {
            model.addAttribute("rightImproveMsg", "个人信息更新成功");

            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            //添加学生活动跟踪日志
            UserDiary userDiary=new UserDiary();
            userDiary.setUserOperate("个人信息更新成功");

            Date now = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
            String timeRecord = dateFormat.format(now);
            userDiary.setUserOperateTime(timeRecord);

            Student studentRecord= (Student) session.getAttribute("studentData");
            userDiary.setUserNo(studentRecord.getStudentNo());

            String stuLoginTime= (String) session.getAttribute("stuLoginTime");
            userDiary.setUserLoginTime(stuLoginTime);
            if(studentService.stuOperateRecord(userDiary)!=0){
                System.out.println("个人信息更新成功已被成功记录"+timeRecord);
            }
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

            UserAvatar userAvatar=new UserAvatar();
            userAvatar.setUserNo(student.getStudentNo());
            model.addAttribute("userAvatar",studentService.JudgeAvatar(userAvatar));
            model.addAttribute("student", studentService.findStudentByNo(student));

            return "studentImproveMsg";
        } else {
            model.addAttribute("errorImproveMsg", "个人信息更新失败");

            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            //添加学生活动跟踪日志
            UserDiary userDiary=new UserDiary();
            userDiary.setUserOperate("个人信息更新失败");

            Date now = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
            String timeRecord = dateFormat.format(now);
            userDiary.setUserOperateTime(timeRecord);

            Student studentRecord= (Student) session.getAttribute("studentData");
            userDiary.setUserNo(studentRecord.getStudentNo());

            String stuLoginTime= (String) session.getAttribute("stuLoginTime");
            userDiary.setUserLoginTime(stuLoginTime);
            if(studentService.stuOperateRecord(userDiary)!=0){
                System.out.println("个人信息更新失败已被成功记录"+timeRecord);
            }
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

            UserAvatar userAvatar=new UserAvatar();
            userAvatar.setUserNo(student.getStudentNo());
            model.addAttribute("userAvatar",studentService.JudgeAvatar(userAvatar));
            model.addAttribute("student", studentService.findStudentByNo(student));

            return "studentImproveMsg";
        }
    }

    //学生查看所有活动
    @RequestMapping("/student/toShowActivity")
    public String toShowActivity(Model model, HttpSession session, Student student) {
        List<Activity> list = studentService.showActivity();
        //model.addAttribute("studentData",(Student)session.getAttribute("studentData"));
        //System.out.println("学生查看所有活动"+student.getStudentNo());
        //model.addAttribute("studentData",student);
        session.getAttribute("studentData");
        model.addAttribute("list", list);
        model.addAttribute("SignUpMsg", session.getAttribute("SignUpMsg"));

        Date now = new Date();//获取当前时间与活动截至日期做对比
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String time = dateFormat.format(now);
        model.addAttribute("nowTime",time);

        return "studentShowActivity";
    }

    //学生报名活动
    @RequestMapping("/student/toSignUp")
    public String toSignUp(ActivityPeople activityPeople, Model model, HttpSession session) {

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String time = dateFormat.format(now);
        activityPeople.setAddTime(time);

        //测试接收到的数据
        System.out.println("学生报名活动"+activityPeople);
        System.out.println(studentService.ifSignUp(activityPeople).isEmpty());

        if (studentService.ifSignUp(activityPeople).isEmpty() ) {//判断是否已经报过名
            if(studentService.signUpActivity(activityPeople) != 0){

                session.setAttribute("allMsgShow", "报名成功");
                //联动活动剩余名额
                //如果已经报过名不可再报
                Activity activity=teacherService.queryActivityByNo(activityPeople.getActivityNo());
                activity.setActivityQuota(activity.getActivityQuota()-1);
                if(studentService.updateActivityQuota(activity)!=0){
                    System.out.println("报名成功，剩余名额已减一");
                }


            }else {
                session.setAttribute("allMsgShow", "报名出错");
            }


            //***************************************************************************************************
            //添加学生活动跟踪日志
            UserDiary userDiary=new UserDiary();
            userDiary.setUserOperate("报名了活动"+activityPeople.getActivityNo());

            Date nowRecord = new Date();
            SimpleDateFormat dateFormatRecord = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
            String timeRecord = dateFormatRecord.format(nowRecord);
            userDiary.setUserOperateTime(timeRecord);

            Student studentRecord= (Student) session.getAttribute("studentData");
            userDiary.setUserNo(studentRecord.getStudentNo());

            String stuLoginTime= (String) session.getAttribute("stuLoginTime");
            userDiary.setUserLoginTime(stuLoginTime);
            if(studentService.stuOperateRecord(userDiary)!=0){
                System.out.println("报名了活动"+activityPeople.getActivityNo()+"已被成功记录"+timeRecord);
            }
            //***************************************************************************************************

        } else {

            session.setAttribute("allMsgShow", "勿复报名");
        }
        //return "redirect:/student/toShowActivity";
        return "allMsgShow";
    }

    //学生查看自己的活动
    @RequestMapping("/student/toMyActivity")
    public String toMyActivity(ActivityPeople activityPeople, Model model,HttpSession session) {
        List<Activity> list = studentService.myActivity(activityPeople);
        model.addAttribute("list", list);
        model.addAttribute("tmpStudentNo", activityPeople.getStudentNo());

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String time = dateFormat.format(now);
        model.addAttribute("nowTime",time);

        return "studentActivity";
    }

    //学生忘记密码
    @RequestMapping("/student/toForgetPwd")
    public String toForgetPwd() {
        return "studentForgetPwd";
    }

    @RequestMapping("/student/forgetPwd")
    public String forgetPwd(Student student, Model model) {
        student = studentService.findStudentByNo(student);
        if (student != null) {
            //发送忘记密码邮件
            String content = "<a href='http://localhost:8080//student/toChangePwd?studentCode=" + student.getStudentCode() +
                    "&studentName=" + student.getStudentName() + "&studentNo=" + student.getStudentNo() + "'>重新设置您在学生素质拓展管理系统的登陆密码</a>" +
                    "<br>或者访问http://localhost:8080//student/toChangePwd?studentCode=" + student.getStudentCode() +
                    "&studentName=" + student.getStudentName() + "&studentNo=" + student.getStudentNo();
            MailUtils.sendMail(student.getStudentEmail(), content, "重新设置密码邮件");
            model.addAttribute("forgetRightMsg", "注意查收邮件进行重新设置密码");
            return "studentForgetPwd";
        } else {
            model.addAttribute("forgetErrorMsg", "发送重新设置密码邮件失败，请联系管理员");
            return "studentForgetPwd";
        }
    }

    @RequestMapping("/student/toChangePwd")
    public String toChangePwd(Student student, Model model) {
        model.addAttribute("student", student);
        return "studentEmailChangePwd";
    }

    @RequestMapping("/student/changePwd")
    public String changePwd(Student student, Model model) {
        //加密密码
        student.setStudentPwd(SecureUtil.md5(student.getStudentPwd()));

        if (studentService.changePwd(student) != 0) {
            model.addAttribute("changeRightMsg", "密码更改成功");
            return "studentEmailChangePwd";
        } else {
            model.addAttribute("changeErrorMsg", "密码更改失败，请联系管理员");
            return "studentEmailChangePwd";
        }
    }

    //学生查看历史公告
    @RequestMapping("/student/toViewHistoryNotice")
    public String toViewHistoryNotice(Model model,HttpSession session) {
        Announcement announcement = new Announcement();
        announcement.setNoticeStatus("F");
        List<Announcement> list = studentService.showNoticeStu(announcement);
        model.addAttribute("list", list);

        return "studentViewAllNotice";
    }

    //学生对公告进行反馈
    @RequestMapping("/student/toFeedBack")
    public String toFeedBack(FeedBack feedBack, Model model,HttpSession session) {
        model.addAttribute("feedBack", feedBack);
        System.out.println("学生对公告进行反馈"+feedBack);

        return "studentFeedBack";
    }

    @RequestMapping("/student/feedBack")
    public String feedBack(FeedBack feedBack, Model model, HttpSession session) {
        Student student = (Student) session.getAttribute("studentData");
        feedBack.setFeedBackNo(student.getStudentNo());
        feedBack.setFeedBackType("S");

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String time = dateFormat.format(now);
        feedBack.setFeedBackTime(time);
        System.out.println("学生对公告进行反馈提交"+feedBack);
        if (studentService.feedBackStu(feedBack) != 0) {
            model.addAttribute("feedBackRightMsg", "已反馈给管理员");

            //***************************************************************************************************
            //添加学生活动跟踪日志
            UserDiary userDiary=new UserDiary();
            userDiary.setUserOperate("对公告反馈成功---"+feedBack.getAdminNotice()+"---");

            Date nowRecord = new Date();
            SimpleDateFormat dateFormatRecord = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
            String timeRecord = dateFormatRecord.format(nowRecord);
            userDiary.setUserOperateTime(timeRecord);

            Student studentRecord= (Student) session.getAttribute("studentData");
            userDiary.setUserNo(studentRecord.getStudentNo());

            String stuLoginTime= (String) session.getAttribute("stuLoginTime");
            userDiary.setUserLoginTime(stuLoginTime);
            if(studentService.stuOperateRecord(userDiary)!=0){
                System.out.println("对公告反馈成功已被成功记录"+timeRecord);
            }
            //***************************************************************************************************

            return "studentFeedBack";
        } else {
            model.addAttribute("feedBackErrorMsg", "出现错误，请重新提交");

            //***************************************************************************************************
            //添加学生活动跟踪日志
            UserDiary userDiary=new UserDiary();
            userDiary.setUserOperate("对公告反馈失败---"+feedBack.getAdminNotice()+"---");

            Date nowRecord = new Date();
            SimpleDateFormat dateFormatRecord = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
            String timeRecord = dateFormatRecord.format(nowRecord);
            userDiary.setUserOperateTime(timeRecord);

            Student studentRecord= (Student) session.getAttribute("studentData");
            userDiary.setUserNo(studentRecord.getStudentNo());

            String stuLoginTime= (String) session.getAttribute("stuLoginTime");
            userDiary.setUserLoginTime(stuLoginTime);
            if(studentService.stuOperateRecord(userDiary)!=0){
                System.out.println("对公告反馈失败已被成功记录"+timeRecord);
            }
            //***************************************************************************************************

            return "studentFeedBack";
        }
    }

    //学生查看自己的反馈
    @RequestMapping("/student/toShowSelfFeedBack")
    public String toShowSelfFeedBack(FeedBack feedBack,Model model,HttpSession session){
        Student student= (Student) session.getAttribute("studentData");
        feedBack.setFeedBackNo(student.getStudentNo());
        List<FeedBack> list=studentService.showFeedBackStu(feedBack);
        model.addAttribute("list",list);

        return "studentShowSelfFeedBack";
    }

    //学生查看自己的学分
    @RequestMapping("/student/toShowSelfScore")
    public String toShowSelfScore(Student student,Model model,HttpSession session){
        List<StudentScore> list=studentService.showSelfScore(student);
        model.addAttribute("list",list);
        model.addAttribute("studentNo",student.getStudentNo());
        System.out.println("学生查看自己的学分"+student.getStudentNo());
        float sumScore=0;
        for(StudentScore studentScore:list){
            sumScore=sumScore+studentScore.getActivityScore();
        }
        model.addAttribute("sumScore",sumScore);

        return "studentSelfScore";
    }

    //学生查看活动详情
    @RequestMapping("/student/toViewActivityDescription")
    public String toViewActivityDescription(Activity activity,Model model,HttpSession session) {
        ActivityDescription activityDescription=teacherService.findActivityDescriptionByNo(activity);
        model.addAttribute("activityDescription",activityDescription);

        return "adminViewActivityDetail";
    }

    //学生查看个人信息
    @RequestMapping("/student/toViewSelfInfo")
    public String toViewSelfInfo(Model model,Student student,HttpSession session){
        student=studentService.findStudentByNo(student);
        model.addAttribute("student",student);


        return "studentViewSelfInfo";
    }

    //根据个人信息生成微信名片
    @RequestMapping("/student/toGenerateInfoCard")
    public String toGenerateInfoCard(Model model,Student student,HttpSession session){
        student=studentService.findStudentByNo(student);
        model.addAttribute("student",student);

        //***************************************************************************************************
        //添加学生活动跟踪日志
        UserDiary userDiary=new UserDiary();
        userDiary.setUserOperate("根据个人信息生成微信名片");

        Date nowRecord = new Date();
        SimpleDateFormat dateFormatRecord = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String timeRecord = dateFormatRecord.format(nowRecord);
        userDiary.setUserOperateTime(timeRecord);

        Student studentRecord= (Student) session.getAttribute("studentData");
        userDiary.setUserNo(studentRecord.getStudentNo());

        String stuLoginTime= (String) session.getAttribute("stuLoginTime");
        userDiary.setUserLoginTime(stuLoginTime);
        if(studentService.stuOperateRecord(userDiary)!=0){
            System.out.println("根据个人信息生成微信名片已被成功记录"+timeRecord);
        }
        //***************************************************************************************************

        return "studentGenerateInfoCard";
    }

    //学生退出登陆
    @RequestMapping("/student/toSignOut")
    public String toSignOut(Student student,HttpSession session){
        UserDiary userDiary=new UserDiary();
        userDiary.setUserNo(student.getStudentNo());
        String stuLoginTime= (String) session.getAttribute("stuLoginTime");
        userDiary.setUserLoginTime(stuLoginTime);
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String time = dateFormat.format(now);
        userDiary.setUserSignOutTime(time);
        if(studentService.stuLogoutRecord(userDiary)!=0){
            System.out.println("退出登录时间成功记录"+time);
        }

        session.removeAttribute("studentData");
        return "studentLogin";
    }

    //学生查看日志
    @RequestMapping("/student/toViewDiary")
    public String toViewDiary(Student student,HttpSession session,Model model){
        List<UserDiary> list=studentService.viewSelfDiary(student);
        model.addAttribute("list",list);

        return "studentOperationDiary";
    }



    //去test
    @RequestMapping("/toTest")
    public String toTest(){
        return "test";
    }
    @RequestMapping("/toTest02")
    public String toTest02(){
        return "test02";
    }
    @RequestMapping("/toTest03")
    public String toTest03(){
        return "test03";
    }
    @RequestMapping("/toTest04")
    public String toTest04(){
        return "test04";
    }
    @RequestMapping("/toTest05")
    public String toTest05(){
        return "test05";
    }
    @RequestMapping("/toTest06")
    public String toTest06(){
        return "test06";
    }
    @RequestMapping("/toTest07")
    public String toTest07(){
        return "NoticeTimeline";
    }
}
